package com.zkj.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 全局控制filter
 * 
 * 编码--utf-8
 * 
 * 缓存--no
 * 
 * @author zkj
 * 
 */
public class GlobalControlFilter implements Filter {

	private FilterConfig filterConfig;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

		this.filterConfig = filterConfig;
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String charSetEncoding = filterConfig
				.getInitParameter("charsetEncoding");
		HttpServletRequest req;
		HttpServletResponse resp;
		try {
			req = (HttpServletRequest) request;
			resp = (HttpServletResponse) response;
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("this is not a http request");
		}
		if (req != null && resp != null) {
			resp.setCharacterEncoding(charSetEncoding);// 只对post请求有效
			resp.setContentType("text/html;charset=" + charSetEncoding);
			resp.setDateHeader("Expires", -1);
			resp.setHeader("Cache-Control", "no-cache");
			resp.setHeader("Pragma", "no-cache");
		}
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

}
